package com.wm.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wm.dao.RoleDao;
import com.wm.dao.RolePermMapper;
import com.wm.entity.RbacRole;
import com.wm.exception.RoleNameExistException;
import com.wm.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl<根据ID查询数据> implements RoleService {
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private RolePermMapper rolePermMapper;


    @Override
    @Transactional
    public void insert(RbacRole role,int[] permIds) {

        //判断角色名是否存在
        if(roleDao.getNumOfName(role.getName())==1){
            throw new RoleNameExistException("角色名:" + role.getName() + "已存在");
        }

        role.setStatus(role.ENABLE);
        roleDao.insert(role);

        for (int permId: permIds) {
          rolePermMapper.add(role.getId(),permId);
        }
    }

    @Override
    public List<RbacRole> getAll() {
        return roleDao.getAll();
    }

    @Transactional(readOnly = true)
    @Override
    public RbacRole selectId(int id) {

        return roleDao.getById(id);
    }

    /**
     * //根据ID删除数据
     *     @Override
     * @param role
     * @param permIds
     */

    public void deleteId(RbacRole role, int[] permIds) {
        int id = role.getId();
        rolePermMapper.delByRoleId(role.getId());
        roleDao.deleteId(id);
    }


    /**
     *  修改
     */

    @Override
    @Transactional(isolation = Isolation.SERIALIZABLE)
    public void UpdateRole(RbacRole role, int[] permIds) {
        role.setStatus("y");

//        roleMapper.update(role);   //Java动态SQL
        RbacRole r = roleDao.getByName(role.getName());

        rolePermMapper.delByRoleId(role.getId());
        if (r != null && r.getId() != role.getId()) {
            throw new RoleNameExistException("角色名重复");
        }

        roleDao.UpdateRole(role);   //Java动态SQL
        rolePermMapper.delByRoleId(role.getId());
        for (int permId : permIds) {
            rolePermMapper.add(role.getId(), permId);
        }


    }

    @Override
    public PageInfo<RbacRole> getByCondition(int pageNum,RbacRole role) {
        PageHelper.startPage(pageNum,5);
        List<RbacRole> roles = roleDao.getAll(role);

        return new PageInfo<>(roles);
    }
}
